from rest_framework import permissions

from Group.models import TeamMemberShip


class IsTeamAdminOrCreator(permissions.BasePermission):
    """
        团队中只有管理员或者创建者能对成员执行的操作
    """

    def has_permission(self, request, view):
        team_id = view.kwargs.get('pk')
        user = request.user
        member = TeamMemberShip.objects.filter(team__id=team_id, person=user)
        if member.exists():
            return member.first().is_admin or member.first().team.creator == user
        return False


class IsTeamMember(permissions.BasePermission):
    # 必须是团队成员才可以访问团队内部
    def has_permission(self, request, view):
        team_id = view.kwargs.get('pk')
        user = request.user
        member = TeamMemberShip.objects.filter(team__id=team_id, person=user)
        return member.exists()


class IsTeamMemberSelfOrAdmin(permissions.BasePermission):
    """
        团队中自己的请求
    """

    def has_permission(self, request, view):
        if request.method == 'GET':
            team_id = view.kwargs.get('pk')
            user = request.user
            member = TeamMemberShip.objects.filter(team__id=team_id, person=user)
            return member.exists()

        team_id = view.kwargs.get('pk')
        user = request.user
        member = TeamMemberShip.objects.filter(team__id=team_id, person=user)

        if not member.exists():
            return False

        if member.first().is_admin or member.first().team.creator == user:
            return True

        member_id = request.kwargs.get('member') if request.kwargs.get('member') else request.data.get('id')

        if member_id:
            return member_id == member.id
        return True


class IsInLab301(permissions.BasePermission):
    def has_permission(self, request, view):
        if request.method == 'GET':
            return True
        elif request.method == 'POST':
            def get_client_ip(request):
                x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
                if x_forwarded_for:
                    ip = x_forwarded_for.split(',')[0]
                else:
                    ip = request.META.get('REMOTE_ADDR')
                return ip

            client_ip = get_client_ip(request)

            print(client_ip)

            return True
